home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Moscow ML 1.42 / src / mosmllib / Dynarray.sml < prev    next >
Encoding:
Text File  |  1997-08-18  |  1.3 KB  |  48 lines  |  [TEXT/R*ch]

  1. (* Modified for Moscow ML from SML/NJ Library 0.2 file dynamic-array.sml
  2.  *
  3.  * COPYRIGHT (c) 1993 by AT&T Bell Laboratories.  
  4.  * See file mosml/copyrght/copyrght.att for details.
  5.  *
  6.  * Arrays of unbounded length
  7.  *
  8.  *)
  9.  
  10. datatype 'elem array = BLOCK of 'elem Array.array ref * 'elem
  11.  
  12. fun array (sz, dflt) = BLOCK(ref (Array.array (sz,dflt)),dflt)
  13.  
  14. fun subArray (BLOCK(arr,dflt),lo,hi) = let
  15.       val arrval = !arr
  16.       fun copy i = (Array.sub(arrval,i+lo)) handle _ => dflt
  17.       in
  18.         BLOCK(ref(Array.tabulate(hi-lo,copy)),dflt)
  19.       end
  20.  
  21. fun fromList (initlist, dflt) = BLOCK(ref (Array.fromList initlist),dflt)
  22.  
  23. fun tabulate (sz,fillfn,dflt) = BLOCK(ref (Array.tabulate (sz,fillfn)),dflt)
  24.  
  25. fun default (BLOCK(_,dflt)) = dflt
  26.  
  27. fun sub (BLOCK(arr,dflt),idx) = (Array.sub(!arr,idx)) 
  28.       handle Subscript => if idx < 0 then raise Subscript else dflt
  29.  
  30. fun bound (BLOCK(arr,_)) = Array.length (!arr)
  31.  
  32. fun expand(arr,oldlen,newlen,dflt) = let
  33.       fun fillfn i = if i < oldlen then Array.sub(arr,i) else dflt
  34.       in
  35.         Array.tabulate(newlen,fillfn)
  36.       end
  37.  
  38. fun update (b as BLOCK(arr,dflt),idx,v) = let 
  39.       fun max(x, y: int) = if x>y then x else y
  40.       val len = bound b
  41.       in
  42.         if idx >= len 
  43.           then arr := expand(!arr,len,max(len+len,idx+1),dflt) 
  44.           else ();
  45.         Array.update(!arr,idx,v)
  46.       end
  47.  
  48.